package com.luych.toolbox.data.service.job;

import com.luych.toolbox.common.enums.*;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketEventPublisher;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketLetterPublisher;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketNoticePublisher;
import com.luych.toolbox.common.feign.intf.base.service.TaskFeign;
import com.luych.toolbox.common.feign.param.base.service.TaskParam;
import com.luych.toolbox.common.feign.param.gateway.center.WebSocketEvent;
import com.luych.toolbox.common.feign.view.base.service.TaskView;
import com.luych.toolbox.common.service.tool.Cmd;
import com.luych.toolbox.data.service.constant.Constant;
import com.luych.toolbox.data.service.dao.DataAgentDao;
import com.luych.toolbox.data.service.dao.DataBackupHistoryDao;
import com.luych.toolbox.data.service.dao.DataSourceDao;
import com.luych.toolbox.data.service.entity.DataAgent;
import com.luych.toolbox.data.service.entity.DataBackupHistory;
import com.luych.toolbox.data.service.entity.DataSource;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.transaction.support.TransactionTemplate;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DataBackupHistoryExecuteJob extends QuartzJobBean {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataBackupHistoryExecuteJob.class);

    private final BusProperties busProperties;
    private final ApplicationEventPublisher applicationEventPublisher;

    private final TransactionTemplate transactionTemplate;

    private final DataBackupHistoryDao dataBackupHistoryDao;
    private final DataSourceDao dataSourceDao;
    private final DataAgentDao dataAgentDao;

    private final TaskFeign taskFeign;

    private String id;

    public DataBackupHistoryExecuteJob(BusProperties busProperties,
                                       ApplicationEventPublisher applicationEventPublisher,
                                       TransactionTemplate transactionTemplate,
                                       DataBackupHistoryDao dataBackupHistoryDao,
                                       DataSourceDao dataSourceDao,
                                       DataAgentDao dataAgentDao,
                                       TaskFeign taskFeign) {
        this.busProperties = busProperties;
        this.applicationEventPublisher = applicationEventPublisher;
        this.transactionTemplate = transactionTemplate;
        this.dataBackupHistoryDao = dataBackupHistoryDao;
        this.dataSourceDao = dataSourceDao;
        this.dataAgentDao = dataAgentDao;
        this.taskFeign = taskFeign;
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        String id = this.id != null ? this.id : context.getJobDetail().getJobDataMap().getString("id");

        WebSocketLetterPublisher letterPublisher = new WebSocketLetterPublisher(busProperties, applicationEventPublisher);
        WebSocketNoticePublisher noticePublisher = new WebSocketNoticePublisher(busProperties, applicationEventPublisher);
        WebSocketEventPublisher eventPublisher = new WebSocketEventPublisher(busProperties, applicationEventPublisher);

        DataBackupHistory backupHistory = dataBackupHistoryDao.findById(id).orElseThrow(() ->
                new JobExecutionException(Constant.DATA_BACKUP_HISTORY_NOT_FOUND));
        DataSource dataSource = dataSourceDao.findById(backupHistory.getDataSourceId()).orElseThrow(() ->
                new JobExecutionException(Constant.DATA_SOURCE_NOT_FOUND));
        DataAgent dataAgent = dataAgentDao.findById(backupHistory.getDataAgentId()).orElseThrow(() ->
                new JobExecutionException(Constant.DATA_AGENT_NOT_FOUND));

        if (!DataSourceStatus.NORMAL.equals(dataSource.getStatus())) {
            LOGGER.info("the data source [{}] status is {}, sleep 10 second and then retry...", dataSource.getName(), dataSource.getStatus());
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                throw new JobExecutionException(e);
            }
            throw new JobExecutionException("need retry", true);
        }

        final DataSourceStatus oldDataSourceStatus = dataSource.getStatus();

        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());

        String mkdirCmd = "mkdir -p " + dataAgent.getPath();

        String backupFile = dataAgent.getPath() + "/" + backupHistory.getFile();
        DataSourceType.Cmd backupCmd = dataSource.getType().getExportCmd(dataSource.getHost(), dataSource.getPort(),
                dataSource.getUser(), dataSource.getPass(), dataSource.getDb(), backupFile);

        transactionTemplate.executeWithoutResult(status -> {
            backupHistory.setStartDate(new Date());
            backupHistory.setStatus(DataBackupHistoryStatus.RUNNING);
            dataBackupHistoryDao.save(backupHistory);

            dataSource.setStatus(DataSourceStatus.BACKUPING);
            dataSourceDao.save(dataSource);
        });

        eventPublisher.send(new WebSocketEvent(WebSocketEvent.Type.DATA_SOURCE_BACKUP_RUNNING, dataSource.getId()));
        eventPublisher.send(new WebSocketEvent(WebSocketEvent.Type.DATA_BACKUP_RUNNING, backupHistory.getId()));

        TaskParam taskParam = new TaskParam();
        taskParam.setType(TaskType.DATA_BACKUP);
        taskParam.setStatus(TaskStatus.PENDING);
        taskParam.setName("备份数据源");
        taskParam.setDescription("备份数据源[" + dataSource.getName() + "]");
        taskParam.setOwnerId(backupHistory.getOwnerId());
        TaskView taskResult = taskFeign.create(taskParam);
        taskFeign.start(taskResult.getId());

        LOGGER.info("start to backup data source [{}]...", dataSource.getUrl());
        String message = "数据备份任务执行通知";
        try {
            Cmd.executeRemote(dataAgent.getHost(), dataAgent.getPort(), dataAgent.getUser(), dataAgent.getPass(), mkdirCmd);
            Cmd.executeRemote(dataAgent.getHost(), dataAgent.getPort(), dataAgent.getUser(), dataAgent.getPass(), backupCmd.getCmd(), backupCmd.getCodes());
            LOGGER.info("success to backup data source [{}]", dataSource.getUrl());

            transactionTemplate.executeWithoutResult(status -> {
                backupHistory.setStatus(DataBackupHistoryStatus.SUCCESS);
                backupHistory.setCompleteDate(new Date());
                dataBackupHistoryDao.save(backupHistory);

                dataSource.setStatus(oldDataSourceStatus);
                dataSourceDao.save(dataSource);
            });

            String content = "数据备份任务[" + backupHistory.getName() + "]于" + datetime + "执行成功！";
            letterPublisher.success(backupHistory.getOwnerId(), message, content);
            noticePublisher.success(backupHistory.getOwnerId(), content);
            eventPublisher.send(new WebSocketEvent(WebSocketEvent.Type.DATA_SOURCE_BACKUP_SUCCESS, dataSource.getId()));
            eventPublisher.send(new WebSocketEvent(WebSocketEvent.Type.DATA_BACKUP_SUCCESS, backupHistory.getId()));

            taskFeign.complete(taskResult.getId(), TaskStatus.SUCCESS, "成功");
        } catch (Exception e) {
            LOGGER.info("error to backup data source [{}]: {}", dataSource.getUrl(), e.getMessage(), e);
            StringWriter writer = new StringWriter();
            e.printStackTrace(new PrintWriter(writer));

            transactionTemplate.executeWithoutResult(status -> {
                backupHistory.setStatus(DataBackupHistoryStatus.FAILED);
                backupHistory.setErrorMessage(e.getMessage());
                backupHistory.setErrorTrace(writer.toString());
                dataBackupHistoryDao.save(backupHistory);

                dataSource.setStatus(oldDataSourceStatus);
                dataSourceDao.save(dataSource);
            });

            String content = "数据备份任务[" + backupHistory.getName() + "]于" + datetime + "执行异常，请及时处理。";
            noticePublisher.error(backupHistory.getOwnerId(), content);
            content += "\n\n\n错误信息：\n" + e.getMessage() + "\n\n\n异常堆栈：\n" + writer;
            letterPublisher.error(backupHistory.getOwnerId(), message, content);
            eventPublisher.send(new WebSocketEvent(WebSocketEvent.Type.DATA_SOURCE_BACKUP_ERROR, dataSource.getId()));
            eventPublisher.send(new WebSocketEvent(WebSocketEvent.Type.DATA_BACKUP_ERROR, backupHistory.getId()));

            taskFeign.complete(taskResult.getId(), TaskStatus.ERROR, e.getMessage());
        }
    }

    public void setId(String id) {
        this.id = id;
    }
}
